package com.app.service.impl;

import com.alibaba.excel.EasyExcel;
import com.app.controller.importExcel.ImportExcelListener;
import com.app.mapper.TestsRecordMapper;
import com.app.model.*;
import com.app.service.DepartmentService;
import com.app.service.TestsRecordService;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.StringTool;
import com.app.util.TestFileUtil;
import com.app.vo.TestsRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.ListUtils;
import org.thymeleaf.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service
@Primary
public class TestsRecordServiceImpl implements TestsRecordService {
    @Autowired
    private TestsRecordMapper testsRecordMapper;
    @Autowired
    private DepartmentService departmentService;

    @Override
    public TestsRecordVo getListByModel(TestsRecordModel model, Integer sortType) {
        QueryWrapper<TestsRecordModel> queryWrapper = new QueryWrapper<>();
        if (StringTool.isNotEmpty(model.getYear())) {
            queryWrapper.eq("year", model.getYear());
        }
        if (model.getDepartmentId()!=null){
            queryWrapper.eq("department_id", model.getDepartmentId());
        }
        if (sortType==null || sortType==1){
            queryWrapper.orderByAsc("number").orderByDesc("crt_time");
        }else {
            queryWrapper.orderByDesc("number").orderByDesc("crt_time");
        }
        Page<TestsRecordModel> page = new Page<>();
        page.setCurrent(model.getPage());
        page.setSize(model.getLimit());
        Page<TestsRecordModel> jobPublishModelPage = testsRecordMapper.selectPage(page, queryWrapper);
        for (int i = 0; i < jobPublishModelPage.getRecords().size(); i++) {
            if (jobPublishModelPage.getRecords().get(i).getDepartmentId() != null) {
                DepartmentModel departmentModel = departmentService.getDepByDepId(jobPublishModelPage.getRecords().get(i).getDepartmentId());
                if (departmentModel != null) {
                    jobPublishModelPage.getRecords().get(i).setDepartmentName(departmentModel.getName());//获取部门名字
                }
            }
        }
        TestsRecordVo vo = new TestsRecordVo();
        vo.setList(jobPublishModelPage.getRecords());
        vo.setCount((int) jobPublishModelPage.getTotal());
        return vo;
    }

    @Override
    public Integer insert(TestsRecordModel model) {
        return testsRecordMapper.insert(model);
    }

    @Override
    public void update(TestsRecordModel model) {
        testsRecordMapper.updateById(model);
    }

    @Override
    public TestsRecordModel getModelById(Integer id) {
        return testsRecordMapper.selectById(id);
    }

    @Override
    public void deleteTestsRecord(Integer id) {
        testsRecordMapper.deleteById(id);
    }

    @Override
    public List<TestsRecordModel> getPlantByIds(List<Integer> appIdList) {
        QueryWrapper<TestsRecordModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select().in("id", appIdList);
        return testsRecordMapper.selectList(queryWrapper);
    }
    // 导入实验记录统计excel文件
//    @Override
//    public String importTestRecord(MultipartFile file) throws IOException {
//        String path = TestFileUtil.getPath()+"excel.xlsx";
//        File localFile = new File(path);
//        file.transferTo(localFile);
//        String filePath = localFile.getAbsolutePath();
//        AtomicReference<Integer> row = new AtomicReference<>(new Integer(0));
//        try {
//            EasyExcel.read(filePath,TestsRecordModel.class,new PageReadListener<TestsRecordModel>(dateList->{
//                for (TestsRecordModel testsRecordModel : dateList) {
//                    DepartmentModel departmentModel = departmentService.getdepByName(testsRecordModel.getDepartmentName());
//                    if (departmentModel != null){
//                        testsRecordModel.setDepartmentId(departmentModel.getId());
//                    }
//                    testsRecordModel.setCrtTime(CommonHelp.getNowTimestamp());
//                    testsRecordMapper.insert(testsRecordModel);
//                }
//                row.set(row.get()+1);
//            })).sheet().headRowNumber(6).doRead();
//        } catch (ExcelDataConvertException e) {
//            Integer rowIndex = e.getRowIndex()+1;
//            Integer columnIndex = e.getColumnIndex()+1;
//            return "模版错误，或者数据错误第"+rowIndex+"行,"+"第"+columnIndex+"列异常";
//        }
//        localFile.delete();
//        return "成功导入" + row + "行。";
//    }

    // 导入实验记录统计excel文件
    @Override
    public String importTestRecord(MultipartFile file) throws IOException {
        List<String> errorList = new ArrayList<>();
        String path = TestFileUtil.getPath() + "excel.xlsx";
        File localFile = new File(path);
        file.transferTo(localFile);
        String filePath = localFile.getAbsolutePath();
        AtomicReference<Integer> row = new AtomicReference<>(new Integer(0));
        try {
            EasyExcel.read(filePath, TestsRecordModel.class, new ImportExcelListener<TestsRecordModel>(dataList -> {
                for (TestsRecordModel testsRecordModel : dataList) {
                    DepartmentModel departmentModel = departmentService.getdepByName(testsRecordModel.getDepartmentName());
                    if (departmentModel != null) {
                        testsRecordModel.setDepartmentId(departmentModel.getId());
                    }
                    testsRecordModel.setCrtTime(CommonHelp.getNowTimestamp());
                    testsRecordMapper.insert(testsRecordModel);
                    row.set(row.get() + 1);
                }
            }, errorList)).sheet().headRowNumber(5).doRead();
        } catch (Exception e) {
            e.printStackTrace();
            return "Excel导入失败";
        }
        localFile.delete();
        if (row.get() == 0) {
            return "导入0条，请检查模版或者数据格式";
        }
        StringBuilder msg =new StringBuilder("成功导入" + row + "行。");
        if (errorList.size() != 0) {
            for (String error : errorList) {
                msg.append(error);
            }
        }
        return msg.toString();
    }

    /**
     * 批量删除记录数据
     * @param ids
     * @return
     */
    @Override
    public Result<Object> deleteBatchByIds(String ids) {
        // 参数校验
        if (StringUtils.isEmpty(ids)) {
            return Result.success("参数为空，无需删除");
        }
        List<Integer> idsList = Arrays.stream(ids.split(","))
                .map(Integer::valueOf)
                .collect(Collectors.toList());
        // 批量删除
        if (!ListUtils.isEmpty(idsList)) {
            testsRecordMapper.deleteBatchIds(idsList);
            return Result.success("批量删除成功");
        } else {
            return Result.success("批量删除失败，数据为空");
        }
    }
}
